package com.dai.nettyserve.netty.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import java.util.List;
import static com.dai.nettyserve.netty.serve.DataServerInHandler.hexStringToAlgorism;
/**
 * 解码
 * DelimiterBasedFrameDecoder  防止 粘包
 * @author 代
 * 2020年10月30日
 */
public class IODecoder extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf result, List<Object> list) throws Exception {
        // 创建一个大小跟接收内容大小一样的byte数组存储接收的数据
        byte[] result1 = new byte[result.readableBytes()];
        // result中存储的是ByteBuf类型的数据，把数据读取到byte[]中
        result.readBytes(result1);
        StringBuilder receiveString = new StringBuilder();
        if (result1[0] == -91) {
            for (byte b : result1) {
                //转化二进制的数据，需要打开下面的这句代码
                receiveString.append(toHex(b));
            }
            int length = hexStringToAlgorism(receiveString.substring(2, 6));
            StringBuilder sb = new StringBuilder();
            while (length * 2 != receiveString.length()) {
                sb.append("{" + receiveString.substring(0, length * 2) + "}");
                receiveString = new StringBuilder(receiveString.substring(length * 2));
                length = hexStringToAlgorism(receiveString.substring(2, 6));
            }
            sb.append("{" + receiveString + "}");
            list.add(sb.toString());
        } else {
            receiveString = new StringBuilder(new String(result1, "UTF-8"));
            list.add(receiveString.toString());
        }
    }

    /**
     * 把字节转化成字符串
     *
     * @param b 要转化的字节
     * @return 转化后的字符串
     */
    public static String toHex(byte b) {
        String result = Integer.toHexString(b & 0xFF);
        if (result.length() == 1) {
            result = '0' + result;
        }
        return result;
    }

    public static void main(String[] args) {
        System.err.println(toHex((byte) -91));
    }
}
